package com.ruoyi.flowable.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.flowable.domain.WfModelTaskCopy;
import com.ruoyi.flowable.domain.bo.TaskCopyUserBo;
import com.ruoyi.flowable.mapper.WfModelTaskCopyMapper;
import com.ruoyi.flowable.service.IWfModelTaskCopyService;
import com.ruoyi.flowable.utils.ModelUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.FlowElement;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 流程实例节点抄送对象Service业务层处理
 *
 * @author siashan
 * @date 2024-04-05
 */
@Service
public class WfModelTaskCopyServiceImpl extends ServiceImpl<WfModelTaskCopyMapper, WfModelTaskCopy> implements IWfModelTaskCopyService {
    /**
     * 保存节点抄送对象
     *
     * @param modelId      模型ID
     * @param copyUserList 抄送列表
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void create(String modelId, BpmnModel bpmnModel, List<TaskCopyUserBo> copyUserList) {
        removeByModelId(modelId);
        if (CollUtil.isNotEmpty(copyUserList)){
            WfModelTaskCopy taskCopy = null;
            for (TaskCopyUserBo bo : copyUserList){
                taskCopy = new WfModelTaskCopy();
                taskCopy.setModelId(modelId);
                FlowElement flowElement = ModelUtils.getFlowElementById(bpmnModel, bo.getNodeKey());
                taskCopy.setNodeKey(bo.getNodeKey());
                taskCopy.setNodeName(flowElement.getName());
                taskCopy.setCopyList(JSON.toJSONString(bo.getUsers()));
                save(taskCopy);
            }
        }
    }

    @Override
    public void removeByModelId(String modelId) {
        LambdaQueryWrapper<WfModelTaskCopy> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WfModelTaskCopy::getModelId,modelId);

        remove(wrapper);
    }

    @Override
    public List<WfModelTaskCopy> selectByModelId(String modelId) {
        LambdaQueryWrapper<WfModelTaskCopy> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WfModelTaskCopy::getModelId,modelId);
        return list(wrapper);
    }
}
